export function createTreeData(_arr, treeRootPid) {
  var nodes = [];
  for (var i in _arr) {
    var item = {
      id: Number(_arr[i].SPBM),
      name: _arr[i].SPMC,
      pid: Number(_arr[i].PID),
      leaf: _arr[i].IS_FINAL == 1 ? 1 : 0
    }
    nodes.push(item);
  }
  
  var groups = {};
  // 按父节点将节点分组
  for (var i in nodes) {
    if (!groups[nodes[i].pid]) {
      groups[nodes[i].pid] = [];
    }
    groups[nodes[i].pid].push(nodes[i]);
    if (treeRootPid && treeRootPid === nodes[i].id) { // 发现传入的根节点id作为节点id时，将根节点设置为该节点的父节点
      treeRootPid = nodes[i].pid;
    }
  }

  var rootNodes = groups[treeRootPid];
  groups[treeRootPid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
  function traverseTreeNodeGroup(treeNodeGroup) {
    for (var i in treeNodeGroup) {
      var node = treeNodeGroup[i];
      if (groups[node.id]) {
        node.children = groups[node.id];
        groups[node.id] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
        traverseTreeNodeGroup(node.children);
      }
    }
  }
  traverseTreeNodeGroup(rootNodes);
  return rootNodes;
}

export function data2treeDG(nodes, treeRootPid) {
  var groups = {};
  // 按父节点将节点分组
  for (var i in nodes) {
    if (!groups[nodes[i].pid]) {
      groups[nodes[i].pid] = [];
    }
    groups[nodes[i].pid].push(nodes[i]);
    if (treeRootPid && treeRootPid === nodes[i].id) { // 发现传入的根节点id作为节点id时，将根节点设置为该节点的父节点
      treeRootPid = nodes[i].pid;
    }
  }

  var rootNodes = groups[treeRootPid];
  groups[treeRootPid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
  function traverseTreeNodeGroup(treeNodeGroup) {
    for (var i in treeNodeGroup) {
      var node = treeNodeGroup[i];
      if (groups[node.id]) {
        node.children = groups[node.id];
        groups[node.id] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
        traverseTreeNodeGroup(node.children);
      }
    }
  }
  traverseTreeNodeGroup(rootNodes);
  return rootNodes;
}

export function getPathById(tree,id,path){
  if(typeof path=='undefined'){
      path=[]
  }
  for(var i=0;i<tree.length;i++){
      var tempPath=[...path]
      tempPath.push(tree[i].id)
      if(tree[i].id==id){
          return tempPath
      }
      if(tree[i].children){
          let reuslt=getPathById(tree[i].children,id,tempPath)
          if(reuslt){
              return reuslt
          }
      }
  }
}